import 'dart:io';

import 'package:flutter/material.dart';
import 'package:study_app/componments/auto_max_text_view.dart';
import 'package:study_app/tools/tools.dart';

class CustomReader extends StatefulWidget {
  final String readText;
  const CustomReader({Key? key, required this.readText}) : super(key: key);
  @override
  State<CustomReader> createState() => _CustomReaderState();
}

class _CustomReaderState extends State<CustomReader> {
  String readStatus = "自定义";
  String readText = "";
  String warningText = "";
  @override
  void dispose() {
    super.dispose();
    if (Platform.isAndroid) {
      _stopRead();
    }
  }

  @override
  void initState() {
    super.initState();
    readText = widget.readText;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text(readStatus),
          actions: [_startReadbutton(), _rightButton()]),
      body: SafeArea(
          child: Column(
        children: [
          AutoMaxTextView(
              onChangeText: (String tex) {
                readText = tex;
              },
              defaultValue: readText)
        ],
      )),
    );
  }

  Widget _rightButton() {
    return TextButton(
        onPressed: () {
          Navigator.pop(context, readText);
        },
        child: const Text("保存", style: TextStyle(color: Colors.white)));
  }

  Widget _startReadbutton() {
    return TextButton(
        onPressed: () {
          _startRead();
        },
        child: const Text("直接阅读", style: TextStyle(color: Colors.white)));
  }

  _startRead() {
    if (readText.length > 3600) {
      setState(() {
        warningText = "阅读文字，一次不能超过3600个字";
      });
    } else {
      setState(() {
        warningText = "";
      });
    }
    Tool.startSpeech(readText);
  }

  _stopRead() {
    Tool.stopSpeech();
  }
}
